﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml.Linq;
using System.Reflection;

namespace Utilities
{
    public class Reader
    {
        static XDocument XMLDocument = new XDocument();

        private string InvokeStringMethod(string assemblyName, string namespaceName, string typeName, string methodName)
        {
            string s = string.Empty;
            try
            {
                // Get the Type for the class
                Type calledType = Type.GetType(namespaceName + "." + typeName + "," + assemblyName);

                // Invoke the method itself. The string returned by the method winds up in s
                s = (String)calledType.InvokeMember(
                                methodName,
                                BindingFlags.InvokeMethod | BindingFlags.Public |
                                    BindingFlags.Static,
                                null,
                                null,
                                null);

                // Return the string that was returned by the called method.
                
            }
            catch (Exception ex)
            {     }
            return s;
        }

        public Reader()
        {
            try
            {
                XMLDocument = XDocument.Load(Utilities.GetInstallationFolder() + "Scheduler.xml");
            }
            catch (Exception ex)
            {
                SQLite.InsertException("Errore lettura xml\r\n");
            }
        }

        public void RunScheduled()
        {
            foreach (XNode node in XMLDocument.Descendants("class"))
            {
                string ClassName = ((XElement)node).Attribute("name").Value;
                string LastRunStr = ((XElement)node).Element("lastDate").Value;
                string DaysToNextStr = ((XElement)node).Element("daysToNext").Value;
                DateTime LastRun = String.IsNullOrEmpty(LastRunStr) ? DateTime.Today.AddDays(-1.0) : DateTime.Parse(LastRunStr);
                Double DaysToNext = String.IsNullOrEmpty(DaysToNextStr) ? 1.0 : Double.Parse(DaysToNextStr);

                if (LastRun.AddDays(DaysToNext) >= DateTime.Now.Date)
                {
                    InvokeStringMethod("GetWMIClasses", "WMI", "Classes", ClassName.Remove(0,6));
                    UpdateData(ClassName);
                }   
            }
        }

        public void UpdateData(string ClassName)
        {
            string LastRunStr = XMLDocument.Descendants("class").First(s => s.Attribute("name").Value.Equals(ClassName)).Element("lastDate").Value;
            string DaysToNextStr = XMLDocument.Descendants("class").First(s => s.Attribute("name").Value.Equals(ClassName)).Element("daysToNext").Value;
            DateTime LastRun = String.IsNullOrEmpty(LastRunStr) ? DateTime.Today.AddDays(-1.0) : DateTime.Parse(LastRunStr);
            Double DaysToNext = String.IsNullOrEmpty(DaysToNextStr) ? 1.0 : Double.Parse(DaysToNextStr);
            (XMLDocument.Descendants("class").First(s => s.Attribute("name").Value.Equals(ClassName))).Element("lastDate").SetValue(DateTime.Today.ToShortDateString());
            //Da tutti i nodi del documento XML prendi il primo con l'attibuto nome=nomeClasse e modifica l'elemento lastDate con NextDate
            XMLDocument.Save(Utilities.GetInstallationFolder() + "Scheduler.xml");
        }

        public void ClearData()
        {
            DateTime lastClear = DateTime.Parse(XMLDocument.Descendants("config").First().Element("lastClear").Value);
            if (DateTime.Today.Subtract(lastClear).Days > 10)
            {
                // TODO
                System.IO.File.Delete(Environment.ExpandEnvironmentVariables("%ProgramFiles%") + "\\WMIService\\Log.txt");
                System.IO.File.Delete(Environment.ExpandEnvironmentVariables("%ProgramFiles%") + "\\WMIService\\WMIService.db");
                System.IO.File.Delete(Environment.ExpandEnvironmentVariables("%ProgramFiles%") + "\\WMIService\\WMIService.dump");

            }
        }
    }
}
